<?php
	
	$flag = false;
	$numRequired = 10;	// num of files required for each kind of data, can change
	$data_baseURL = "http://localhost/live-syd-traffic/traffic/traffic-data/Incidents/";
	$incidentURL = "../traffic-data/Incidents";
	$F3URL = "../traffic-data/F3";
	$M4URL = "../traffic-data/M4";
	$M7URL = "../traffic-data/M7";
	
	$numIncident;
	$numF3;
	$numM4;
	$numM7;
	
	
	function countNumFilesOfDir($url){
		$filecount = 0;
		$dir = opendir($url);
		if(!$dir){
			return -1;
		}
		while (($file = readdir($dir)) !== false) {
        	if ($file[0] == '.'){
        		continue; 
			}
        	if (is_dir($url.$file)){       
            	$filescount += filecount($FolderPath.$file.DIRECTORY_SEPARATOR);                       
        	}else {
            	$filecount++;
        	}
   		}   
    	closedir($dir);
     	return $filecount;
	}
	
	function findFiles($url, $interval){
		$dir = opendir($url);
		if(!$dir){
			return -1;
		}
		$count = 0;
		$retArr = array();
		while(($file = readdir($dir)) !== false){
			if ($file[0] == '.'){
        		continue; 
			}
			if (is_dir($url.$file)){
				                             
        	}else {
            	if($count%$interval == 0){
            		array_push($retArr,$file);
            	}
            	$count++;
        	}
		}
		return $retArr;
	}
	
	function countFiles(){
		global $numIncident, $numF3, $numM4, $numM7, $incidentURL, $F3URL, $M4URL, $M7URL;
		$numIncident = countNumFilesOfDir($incidentURL);
		$numF3 = countNumFilesOfDir($F3URL);
		$numM4 = countNumFilesOfDir($M4URL);
		$numM7 = countNumFilesOfDir($M7URL);
	}
	
	// open directory incidents to get all the files
	// create and return array of selected incidents
	function openIncidents(){
		global $numIncident, $numRequired, $incidentURL;
		$interval = floor($numIncident/$numRequired);
		$arrayOfFiles = findFiles($incidentURL,$interval);
		print_r($arrayOfFiles);	
	}
	
	// same as incidents but deprecated in this server
	function openF3(){
		global $numF3, $numRequired, $F3URL;
		$interval = floor($numF3/$numRequired);
		$arrayOfFiles = findFiles($F3URL,$interval);
		print_r($arrayOfFiles);	
	}
	
	function openM4(){
		global $numM4, $numRequired, $M4URL;
		$interval = floor($numM4/$numRequired);
		$arrayOfFiles = findFiles($M4URL,$interval);
		
	}
	
	function openM7(){
		global $numM7, $numRequired, $M7URL;
		$interval = floor($numM7/$numRequired);
		$arrayOfFiles = findFiles($M7URL,$interval);
		print_r($arrayOfFiles);	
	}
	
	
	
	
	// executions below:
	
	if($flag == true){
		echo "Incident files : ".countNumFilesOfDir($incidentURL)."<br>";
		echo "F3 files: ".countNumFilesOfDir($F3URL)."<br>";
		echo "M4 files: ".countNumFilesOfDir($M4URL)."<br>";
		echo "M7 files: ".countNumFilesOfDir($M7URL)."<br>";
	}
	countFiles();
	echo openIncidents();
?>